import store from '@/store'
import config from '@/config'
import {
	
	getToken,
	getIsMobile,
	setToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams,
	showokConfirm
} from '@/utils/common'

import {
	nowTtime,
	getASCII
} from '@/utils/index'

let timeout = 10000
const baseUrl = config.baseUrl

const loginUrl = "/common/login"
const userinfoUrl = "/member/mine"
const uploadUrl = "/member/upload"

const whiteList = [
	"/common/login",
	"/member/mine",
	"/member/upload",
	"/member/renew",
	"/member/sms",
	"/member/bindMobile",
	"mine/info/index"
]

// 放开手机号绑定接口
function checkWhite(url) {

	return whiteList.indexOf(url) !== -1
}



// return whiteList.indexOf(path)


const request = config => {

	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	// console.log(">>>token", getToken())
	// const token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImlzc3VlU2lnbktleSI6IjRiOWMwZTI0ZGRhNGQ0NjgzOTYzZTEyNjkxOWE3YTBjIn0.eyJpc3MiOiJodHRwOi8vYXBpMi5kb3lvYWQuY29tIiwidWlkIjoxODQ1LCJpYXQiOjE3MzQ2MjU1MzMuMzk2NzMyLCJleHAiOjE3MzU5MjE1MzMuMzk2NzMyfQ.tKhOnNQLeEejUblQeNS8nf7UbLwYqvB-XlwoJxse72Y";
	// setToken(token)
	if (getToken() && !isToken) {
		// config.header['Authorization'] = 'Bearer ' + getToken()
		config.header['token'] = getToken()
		// config.header['token'] = token
		// config.header['token'] = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImlzc3VlU2lnbktleSI6IjRiOWMwZTI0ZGRhNGQ0NjgzOTYzZTEyNjkxOWE3YTBjIn0.eyJpc3MiOiJodHRwczovL29mZmljZS5kb3lvYWQuY29tIiwidWlkIjo4Njg1NCwiaWF0IjoxNzQyMjIyMjc0Ljg0NzY0NCwiZXhwIjoxNzQzNTE4Mjc0Ljg0NzY0NH0.urTq4JvVvdP6DSKty0YHyX0Lb0y7KkY5d34rLvymvXY"
	}
	var timestamp = nowTtime()
	var sign_arr = {
		timestamp: timestamp
	}
	if (config.data) {
		sign_arr = Object.assign(sign_arr, config.data)
	}

	config.header['timestamp'] = timestamp

	// console.info('getIsMobile()', getIsMobile())

	if (!checkWhite(config.url) && getToken() && !getIsMobile()) {
		uni.reLaunch({
			url: '/pagesA/mine/info/index'
		})
		return false
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url

		sign_arr = Object.assign(sign_arr, config.params)
	}

	var sign = getASCII(sign_arr)
	config.header['sign'] = sign


	return new Promise((resolve, reject, loading = true) => {

		if (loading) {
			uni.showLoading({
				title: '加载中...'
			})
		}


		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				data: config.data,
				header: config.header,
				dataType: 'json'
			}).then(response => {

				if (loading) {
					uni.hideLoading();
				}

				let [error, res] = response
				if (error) {
					toast('后端接口连接异常')
					reject('后端接口连接异常')
					return
				}
				const code = res.data.code || 200
				const msg = errorCode[code] || res.data.msg || errorCode['default']
				if (code === 888 || code === 401) {
					showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
						if (res.confirm) {
							store.dispatch('LogOut').then(res => {
								uni.reLaunch({
									url: '/pagesA/login'
								})
							})
						}
					})
					reject('无效的会话，或者会话已过期，请重新登录。')
				} else if (code === 500) {
					toast(msg)
					reject('500')
				} else if (code !== 200) {
					toast(msg)
					// reject(code)
				}
				resolve(res.data)
			})
			.catch(error => {
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				if (loading) {
					uni.hideLoading();
				}
				toast(message)
				reject(error)
			})
	})
}

export default request